//
//  UIImage+.m
//  EIP
//
//  Created by mac on 15/3/19.
//  Copyright (c) 2015年 Leo. All rights reserved.
//

#import "UIImage+Custom.h"

@implementation UIImage(Custom)

+ (UIImage*)loadingResourcePath:(NSString*)imageName {
    
    NSString* imagePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: imageName];
    return [UIImage imageWithContentsOfFile: imagePath];
}

+ (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize {
    
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
                                
    return scaledImage;
                                
}

+ (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}


////////scale width/height的比例值
+ (UIImage *)cutOutNewImage:(UIImage *)originalImage withScale:(CGFloat)scale
{
    //定义myImageRect，截图的区域
    if (!originalImage) {
        return nil;
    }
    
    CGRect myImageRect;
    CGSize size;
    CGFloat orignalHeight = originalImage.size.height;
    CGFloat orignalWidth  = originalImage.size.width;
    
    if (orignalWidth/orignalHeight == scale) {
        return originalImage;
    }
    else if (orignalWidth/orignalHeight > scale) {
        myImageRect = CGRectMake((orignalWidth-orignalHeight*scale)/2, 0, orignalHeight*scale, orignalHeight);
        size.width = orignalHeight * scale;
        size.height = orignalHeight;
    }
    else{
        //        myImageRect = CGRectMake(0, (orignalHeight-orignalWidth/scale)/2, orignalWidth, orignalWidth/scale);
        //        size.width = orignalWidth;
        //        size.height = orignalWidth/scale;
        
        myImageRect = CGRectMake(0, 0, orignalWidth, orignalWidth/scale);
        size.width = orignalWidth;
        size.height = orignalWidth/scale;
    }
    CGImageRef imageRef = originalImage.CGImage;
    CGImageRef subImageRef = CGImageCreateWithImageInRect(imageRef, myImageRect);
    UIGraphicsBeginImageContext(size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawImage(context, myImageRect, subImageRef);
    
    UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];
    UIGraphicsEndImageContext();
    CGImageRelease(subImageRef);
    return smallImage;
}

@end
